<?php
class Controller_Admin_Banner extends Controller_Admin_Layout
{
    /**
     * Index
     *
     * @access public
     */
    public function action_index($page = 1)
    {
        $pager = new Doctrine_Pager(
                Doctrine_Query::create()
                    ->from('Ads a')
                    ->orderby('a.id DESC'),
                $page
                );

        $pager->getExecuted();
        $banner = $pager->execute();

        $page_ranger = new Doctrine_Pager_Range_Sliding(array('chunk' => 5),
                    $pager);

        $pagination = new Doctrine_Pager_Layout($pager, $page_ranger, Url::site('admin/banner/index/{%page}'));
        $pagination->setTemplate('<a href="{%url}" class="number" title="Trang {%page}">{%page}</a>');
        $pagination->setSelectedTemplate('<a href="{%url}" class="number current" title="Trang {%page}">{%page}</a>');
        
        $this->template->main = View::factory('admin/banner', array(
            'banners' => $banner
        ));
    }

    /**
     * Add a new banner to database
     *
     * @access public
     */
    public function action_create()
    {
        if($this->request->method() === 'POST')
        {
            $post = Validation::factory($_FILES)
                    ->rule('image', 'Upload::not_empty')
                    ->rule('image', 'Upload::size', array($_FILES['image'], '1M'))
                    ->rule('image', 'Upload::type', array($_FILES['image'], array('jpg', 'png', 'gif')))
                    ;

            if($post->check() == TRUE)
            {
                // Save file successully
                $uploaded = Upload::save($_FILES['image'], NULL, Kohana::config('ads.upload_path'));
                if($uploaded !== FALSE)
                {
                    $post = Arr::extract($_POST, array('url', 'type'));
                    $ads = new Ads();
                    $ads->image = basename($uploaded);
                    $ads->url   = $post['url'];
                    $ads->type  = $post['type'];
                    try
                    {
                        $ads->save();
                    }
                    catch(Exception $ex)
                    {
                        // TODO: Handle exception
                    }
                }
            }
        }
        $this->request->redirect(Url::site('admin/banner'));
    }
}